package org.zjx.message;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.annotation.JSONType;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@Data
@JSONType(seeAlso = {HeartbeatMessage.class, CommandMessage.class, ResponseMessage.class, NotificationMessage.class, ActionMessage.class})
public abstract class Message {
    protected String messageId;
    protected long timestamp;
    protected MessageType type;

    public enum MessageType {
        HEARTBEAT, COMMAND, RESPONSE, ACTION, ERROR, NOTIFICATION
    }

    public String toJsonString() {
        return JSON.toJSONString(this, JSONWriter.Feature.WriteClassName);
    }

    public static Message parse(String json) {
        try {
            return JSON.parseObject(json, Message.class);
        } catch (Exception e) {
            System.err.println("Error parsing message: " + json);
            throw new JSONException("Failed to parse message", e);
        }
    }
}